#include "frmmain.h"
#include "frmserialport.h"
#include "frmtcpclient.h"
#include "frmdeviceconfig.h"
#include "frmdeviceupdate.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QDebug>

frmmain::frmmain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::frmmain),
    navButtonGroup(new QButtonGroup(this)),
    serialPort(this),
    tcpSocket(this),
    isSerialConnected(false),
    isTcpConnected(false),
    serialBuffer(""),
    tcpBuffer(""),
    serialPortPage(nullptr),
    tcpClientPage(nullptr),
    deviceConfigPage(nullptr),
    deviceUpdatePage(nullptr)
{
    ui->setupUi(this);

    // 设置清空按钮样式（与其他按钮保持一致）
    ui->btnClearDisplay->setCheckable(false);
    connect(ui->btnClearDisplay, &QPushButton::clicked, this, &frmmain::on_btnClearDisplay_clicked);
    connect(ui->btnFactoryReset, &QPushButton::clicked, this, &frmmain::on_btnFactoryReset_clicked);

    // 设置按钮为可选中
    ui->btnSerialPort->setCheckable(true);
    ui->btnTcpClient->setCheckable(true);
    ui->btnDeviceConfig->setCheckable(true);
    ui->btnDeviceUpdate->setCheckable(true);

    // 初始化按钮组
    navButtonGroup->addButton(ui->btnSerialPort, 0);
    navButtonGroup->addButton(ui->btnTcpClient, 1);
    navButtonGroup->addButton(ui->btnDeviceConfig, 2);
    navButtonGroup->addButton(ui->btnDeviceUpdate, 3);

    // 设置按钮组互斥
    navButtonGroup->setExclusive(true);

    // 设置按钮样式
    QString buttonStyle = R"(
        QPushButton {
            background-color: #F0F0F0;
            border: 1px solid #CCCCCC;
            border-radius: 5px;
            padding: 5px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #E0E0E0;
        }
        QPushButton:checked {
            background-color: #4A90E2;
            color: white;
            border: 1px solid #3A80E0;
        }
    )";

    ui->btnSerialPort->setStyleSheet(buttonStyle);
    ui->btnTcpClient->setStyleSheet(buttonStyle);
    ui->btnDeviceConfig->setStyleSheet(buttonStyle);
    ui->btnDeviceUpdate->setStyleSheet(buttonStyle);

    // 默认选中第一个按钮
    ui->btnSerialPort->setChecked(true);

    // 动态创建自定义控件
    serialPortPage = new frmserialport(this);
    tcpClientPage = new frmtcpclient(this);
    deviceConfigPage = new frmdeviceconfig(this);
    deviceUpdatePage = new frmdeviceupdate(this);

    // 将自定义控件添加到 stackedWidget 的页面
    ui->pageSerialPort->layout()->addWidget(serialPortPage);
    ui->pageTcpClient->layout()->addWidget(tcpClientPage);
    ui->pageNtripConfig->layout()->addWidget(deviceConfigPage);
    ui->pageMqttConfig->layout()->addWidget(deviceUpdatePage);

    // 初始化界面
    ui->responseTextEdit->append(QString::fromUtf8("上位机启动"));

    // 连接信号和槽
    connect(&serialPort, &QSerialPort::readyRead, this, &frmmain::on_serialPort_readyRead);
    connect(&serialPort, &QSerialPort::errorOccurred, this, &frmmain::on_serialPort_error); // 新增
    connect(&tcpSocket, &QTcpSocket::connected, this, &frmmain::on_tcpSocket_connected);
    connect(&tcpSocket, &QTcpSocket::disconnected, this, &frmmain::on_tcpSocket_disconnected);
    connect(&tcpSocket, &QTcpSocket::readyRead, this, &frmmain::on_tcpSocket_readyRead);
    connect(&tcpSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, &frmmain::on_tcpSocket_error);
    connect(navButtonGroup, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &frmmain::on_navButtonClicked);
}

frmmain::~frmmain()
{
    if (isSerialConnected && serialPort.isOpen()) {
        disconnect(&serialPort, &QSerialPort::errorOccurred, 0, 0);
        disconnect(&serialPort, &QSerialPort::readyRead, 0, 0);
        serialPort.close();
    }
    if (isTcpConnected && tcpSocket.state() == QAbstractSocket::ConnectedState) {
        tcpSocket.disconnectFromHost();
    }
    delete serialPortPage;
    delete tcpClientPage;
    delete deviceConfigPage;
    delete deviceUpdatePage;
    delete ui;
}

void frmmain::on_serialPort_error(QSerialPort::SerialPortError error)
{
    Q_UNUSED(error);
    ui->responseTextEdit->append(QString::fromUtf8("串口错误: ") + serialPort.errorString());
    qDebug() << "串口错误: " << serialPort.errorString();
}

void frmmain::on_navButtonClicked(int index)
{
    if (index >= 0 && index < ui->stackedWidget->count()) {
        ui->stackedWidget->setCurrentIndex(index);
    } else {
        ui->responseTextEdit->append(QString::fromUtf8("错误：页面索引无效"));
    }
}

void frmmain::on_serialPort_readyRead()
{
    qDebug() << "on_serialPort_readyRead 触发，串口状态: " << (serialPort.isOpen() ? "打开" : "关闭");
    if (!serialPort.isOpen()) {
        qDebug() << "串口已关闭，忽略 readyRead 信号";
        return;
    }

    serialBuffer += QString::fromUtf8(serialPort.readAll());
    qDebug() << "frmmain 收到串口原始数据: " << serialBuffer;

    QStringList messages;
    if (serialBuffer.contains("\r\n")) {
        messages = serialBuffer.split("\r\n", QString::SkipEmptyParts);
        serialBuffer.clear();
    } else if (serialBuffer.contains("\n")) {
        messages = serialBuffer.split("\n", QString::SkipEmptyParts);
        serialBuffer.clear();
    } else {
        messages << serialBuffer;
        serialBuffer.clear();
    }

    for (const QString &message : messages) {
        QString trimmedMessage = message.trimmed();
        if (!trimmedMessage.isEmpty()) {
            qDebug() << "frmmain 发出信号: " << trimmedMessage;
            ui->responseTextEdit->append(QString::fromUtf8("串口接收: ") + trimmedMessage);
            emit serialDataReceived(trimmedMessage);
        }
    }
}

void frmmain::on_tcpSocket_connected()
{
    setIsTcpConnected(true);
    ui->responseTextEdit->append(QString::fromUtf8("TCP 连接成功"));
}

void frmmain::on_tcpSocket_disconnected()
{
    setIsTcpConnected(false);
    ui->responseTextEdit->append(QString::fromUtf8("TCP 连接断开"));
}

void frmmain::on_tcpSocket_readyRead()
{
    tcpBuffer += QString::fromUtf8(tcpSocket.readAll());
    qDebug() << "frmmain 收到原始数据: " << tcpBuffer;

    QStringList messages;
    if (tcpBuffer.contains("\r\n")) {
        messages = tcpBuffer.split("\r\n", QString::SkipEmptyParts);
        tcpBuffer.clear();
    } else if (tcpBuffer.contains("\n")) {
        messages = tcpBuffer.split("\n", QString::SkipEmptyParts);
        tcpBuffer.clear();
    } else {
        messages << tcpBuffer;
        tcpBuffer.clear();
    }

    for (const QString &message : messages) {
        QString trimmedMessage = message.trimmed();
        if (!trimmedMessage.isEmpty()) {
            qDebug() << "frmmain 发出信号: " << trimmedMessage;
            ui->responseTextEdit->append(QString::fromUtf8("TCP 接收: ") + trimmedMessage);
            emit tcpDataReceived(trimmedMessage);
        } else {
            qDebug() << "frmmain 收到空消息，跳过";
        }
    }
}

void frmmain::on_tcpSocket_error(QAbstractSocket::SocketError error)
{
    ui->responseTextEdit->append(QString::fromUtf8("TCP 错误: ") + tcpSocket.errorString());
    qDebug() << "TCP 错误: " << tcpSocket.errorString();
}

void frmmain::on_btnClearDisplay_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认", "确定清空所有显示内容吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        ui->responseTextEdit->clear();
    }
}

void frmmain::on_btnFactoryReset_clicked()
{
    QMessageBox::StandardButton reply = QMessageBox::question(this, "恢复出厂配置", "确定要恢复出厂配置吗？此操作不可撤销！", QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        bool sent = false;
        if (isSerialConnected && serialPort.isOpen()) {
            serialPort.write("$RES\r\n");
            serialPort.flush();
            sent = true;
            ui->responseTextEdit->append("已通过串口发送恢复出厂配置指令: $RES");
        } else if (isTcpConnected && tcpSocket.state() == QAbstractSocket::ConnectedState) {
            tcpSocket.write("$RES\r\n");
            tcpSocket.flush();
            sent = true;
            ui->responseTextEdit->append("已通过TCP发送恢复出厂配置指令: $RES");
        }
        if (!sent) {
            QMessageBox::warning(this, "错误", "未检测到可用的串口或TCP连接，无法发送恢复出厂配置指令。");
            ui->responseTextEdit->append("错误：未检测到可用的串口或TCP连接，无法发送恢复出厂配置指令。");
        }
    }
}
